package com.parmal.proxy.server;

import com.parmal.proxy.configuration.HttpProxyConfiguration;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class HttpProxyForwardStarter extends ProxyStarter {

    private HttpProxyConfiguration configuration;

    private Bootstrap bootstrap;

    private NioEventLoopGroup worker;

    @Autowired
    public HttpProxyForwardStarter(HttpProxyConfiguration configuration) {
        this.configuration = configuration;
        this.init();
    }

    @Override
    protected void init() {
        this.worker = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);
        this.bootstrap = new Bootstrap();
        bootstrap.group(worker);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new HttpRequestEncoder());
                socketChannel.pipeline().addLast(new HttpObjectAggregator(65536));
            }
        });
    }

    @Override
    @Bean
    public Bootstrap start() {
        return this.bootstrap;
    }
}
